$(function () {
	var openNum = 0;
	var useArray = []
	var timer = -1;
	query()
    var Obj = {};
    Obj.luckyResult = [];
    Obj.luckyPrize = '';
    Obj.luckyNum = parseInt($(".tit_input input").val()) ;
    
    $(".tit_input input").bind('change', function () {
    	if ($(".tit_input input").val() > 8) {
    		alert("最大只能输入8")
    		$(".tit_input input").val(8)
    	}
        Obj.luckyNum = $(".tit_input input").val();
    })
    /*
     �丞��蘂���莉�
     */
    function loadImage(arr, callback) {
        var loadImageLen = 1;
        var arrLen = arr.length;
        $('.all_number').html("/" + arrLen);
        $('.loader_file').hide();
        for (var i = 0; i < arrLen; i++) {
            var img = new Image(); //��綮坂�筝�Image絲壕院鐚�絎��ｰ�丞����蘂�筝�莉�
            /*img.onload = function () {
                img.onload = null;
                ++loadImageLen;
                $(".current_number").html(loadImageLen);

                if (loadImageLen == arrLen) {
                    callback(img); //�����丞����莉醇������莪�鐚�
                }
                ;
            }
            img.src = arr[i].image;*/
        }
    }

    /*
     ��3D���糸��紮���鐚�膈�緇��ц�
     useArray筝堺���医��ユ�井��
     */
    loadArr()
    function loadArr() {
    	Obj.M = $('.container').lucky({
	        row: 7, //罸����丞ず筝���  綽�蕁私減絅���
	        col: 5,//罸����丞ず筝���  綽�蕁私減絅���
	        depth: 5, //膾究訓綺�
	        iconW: 30, //�丞����絎�
	        iconH: 30, //�丞����蕭�
	        iconRadius: 8, //�丞������茹�
	        data: useArray, //�井�����医���亥�
	    });
    }
    
    /*
    �ц��丞��蘂���莉遵攻�渇�㊤��莉処���
    */
    loadImage(useArray, function (img) {
        $('.loader_file').hide();
    });
  
    function showLuckyPeople(num) {
        setTimeout(function () {
            /*var $luckyEle = $('<img class="lucky_icon" />');*/
            var $userName = $('<p class="lucky_userName"></p>');
            var $fragEle = $('<div class="lucky_userInfo"></div>');
            $fragEle.append( $userName);
            $userName.css('color','#ffff04').css('font-size','50px')
            $('.mask').append($fragEle);
            console.log($('.mask'),$fragEle)
            timer = 10
            $(".mask").fadeIn(200);
            //$luckyEle.attr('src', useArray[Obj.luckyResult[num]].image);
            $userName.text('')
            $userName.text(useArray[Obj.luckyResult[num]].address + ' '+ useArray[Obj.luckyResult[num]].name)
            $fragEle.animate({
                'left': '50%',
                'top': '50%',
                'height': '200px',
                'width': '500px',
                'margin-left': '-250px',
                'margin-top': '-100px',
            }, 1000, function () {
                setTimeout(function () {
                    $fragEle.animate({
                        'height': '100px',
                        'width': '500px',
                        'margin-left': '100px',
                        'margin-top': '-50px',
                    }, 400, function () {
                        $(".mask").fadeOut(0);
                        $userName.attr('class', 'lpl_userName').attr('style', '');
                        $fragEle.attr('class', 'lpl_userInfo').attr('style', '').css('display','none');
                        var divHtml = "<div style='display:inline-block; width:50%;text-align:right;'>"+useArray[Obj.luckyResult[num]].address +" &nbsp; </div><div style='display:inline-block;width:50%;text-align:left;'>"+useArray[Obj.luckyResult[num]].name +" </div>"
                        //$('#plist').append("<li>"+useArray[Obj.luckyResult[num]].address + ' '+ useArray[Obj.luckyResult[num]].name+"</li>")
                        $('#plist').append("<li>"+divHtml+"</li>")
                    	if (parseInt($('#topContent').attr('index')) == 1) {
                    		if (!localStorage.getItem('persons')) {
                    			removePerson('persons',useArray[Obj.luckyResult[num]].id, personArray)
                    		} else {
                    			removePerson('persons',useArray[Obj.luckyResult[num]].id, JSON.parse(localStorage.getItem('persons')))
                    		}
                    	} else if (parseInt($('#topContent').attr('index')) == 0 || !$('#topContent').attr('index')) {
                    		if (!localStorage.getItem('boss')) {
                    			removePerson('boss',useArray[Obj.luckyResult[num]].id, bossArray)
                    		} else {
                    			removePerson('boss',useArray[Obj.luckyResult[num]].id, JSON.parse(localStorage.getItem('boss')))
                    		}
                    	} else if (parseInt($('#topContent').attr('index')) == 2) {
                    		if (!localStorage.getItem('all')) {
                    			removePerson('all',useArray[Obj.luckyResult[num]].id, personArray)
                    		} else {
                    			removePerson('all',useArray[Obj.luckyResult[num]].id, JSON.parse(localStorage.getItem('all')))
                    		}
                    	}
                    })
                }, 1000)
            })
        }, num * 2500)
        setTimeout(function () {
            $('.box').show();
        }, 2500)
        setTimeout(function() {
        	 timer = -1
        },Obj.luckyNum*2500)
    }
	
	function removePerson(name,content, arr) {
		var newArr = []
		arr.forEach(function(item, index){
			if (item.id == content) {
				localStorage.setItem($('#topContent').text() + $('#bottomContent').text()+item.id, JSON.stringify(item))
			} else {
				newArr.push(item)
			}
		})
		localStorage.setItem(name, JSON.stringify(newArr))
	}
    /*
     ��罩∽�����篁九�醇��
     */
    $('#stop').click(function () {
        Obj.M.stop();
        $(".container").hide();
        $(this).hide();
        var i = 0;
        for (; i < Obj.luckyResult.length; i++) {
            showLuckyPeople(i);
        }
    })
    /*
     綣�紮������篁九�醇��
     */
	function beginOpen() {
		$("#plist").html('')
		Obj.luckyNum = parseInt($(".tit_input input").val()) ;
		if (parseInt($('#topContent').attr('index')) == 1) {
    		if (!localStorage.getItem('persons')) {
    			useArray = personArray
    		} else {
    			useArray = JSON.parse(localStorage.getItem('persons'))
    		}
    	} else if (parseInt($('#topContent').attr('index')) == 0 || !$('#topContent').attr('index')) {
    		if (!localStorage.getItem('boss')) {
    			useArray =  bossArray
    		} else {
    			useArray =  JSON.parse(localStorage.getItem('boss'))
    		}
    	} else if (parseInt($('#topContent').attr('index')) == 2) {
    		if (!localStorage.getItem('all')) {
    			useArray =  personArray
    		} else {
    			useArray =  JSON.parse(localStorage.getItem('all'))
    		}
    	}
    	loadArr()
	}
	
	$("body").keydown(function() {
		console.log(timer)
		if ($("#stop").css('display') == 'none' ) {
			if (timer != 10) {
				if (event.keyCode == "13") {//keyCode=13是回车键；数字不同代表监听的按键不同
			       return  $('#open').click()
			    }
			}
		} else {
			if (event.keyCode == "32") {
		    	return  $('#stop').click()
		    }
		}
	});
    $('#open').click(function () {
    	beginOpen()
    	if (parseInt($(".tit_input input").val()) >  useArray.length){
    		alert("只剩下"+useArray.length+"人未获得奖品,请修改获奖人数")
    		location.reload();
    		return;
    	}
        $('.box').hide();
        $(".container").show();
        Obj.M.open();
        randomLuckyArr();
        setTimeout(function () {
            $("#stop").show(500);
        }, 1000)
        //篋阪轡�ｷ絅�膸���膸���
    })

    /*
     ��腴���筝㊤����堺��
     */
    function randomLuckyArr() {
        Obj.luckyResult = [];
        for (var i = 0; i < Obj.luckyNum; i++) {
            var random = Math.floor(Math.random() * useArray.length);
            if (Obj.luckyResult.indexOf(random) == -1) {
                Obj.luckyResult.push(random)
            } else {
                i--;
            }
        }
        console.log(Obj.luckyResult)
    }

    /*
     ���√���篁ｇ����
     */
    function tabPrize() {
        var luckyDefalut = $(".lucky_prize_picture").attr('data-default');
        var index = luckyDefalut ? luckyDefalut : 1;
        tabSport(index);
        var lucky_prize_number = $('.lucky_prize_show').length;
        $('.lucky_prize_left').click(function () {
            $('.lucky_prize_right').addClass('active');
            index <= 1 ? 1 : --index;
            tabSport(index, lucky_prize_number);
        })
        $('.lucky_prize_right').click(function () {
            $('.lucky_prize_left').addClass('active');
            index >= lucky_prize_number ? lucky_prize_number : ++index;
            tabSport(index, lucky_prize_number);
        })

    }

    /*
     ���√���綏�勄�������掩─��
     */
    function tabSport(i, lucky_prize_number) {
        if (i >= lucky_prize_number) {
            $('.lucky_prize_right').removeClass('active');
        }
        if (i <= 1) {
            $('.lucky_prize_left').removeClass('active');
        }
        Obj.luckyPrize = i;
        $('.lucky_prize_show').hide().eq(i - 1).show();
        $(".lucky_prize_title").html($('.lucky_prize_show').eq(i - 1).attr('alt'));
        $('.lpl_list').removeClass('active').hide().eq(i - 1).show().addClass('active');
    }
    tabPrize();
    function query() {
    	useArray = personArray
    	$('#joinNum').text(useArray.length + ' 人');
    	$('#topContent').html(CONSTS.TYPE[1]).attr('index',1)
    	$('#bottomContent').html('特等奖').attr('index',0)
    	$(".tit_input input").val(1)
    	localStorage.setItem('originBoss',JSON.stringify(bossArray) )
    	localStorage.setItem('originTeam', JSON.stringify(personArray))
    }
    $('#resetData').dblclick(function() {
    	if (confirm('确定重置吗？')) {
    		localStorage.clear()
    		location.reload();
    	} 
    })
    /*resetData*/
    $("#topLeft").click(function() {
    	/*var index = parseInt($('#topContent').attr('index'))
    	if (0 == index) {
    		index = CONSTS.TYPE.length-1
    	} else {
    		index--
    	}
    	if (index == 0) {
    		$('#joinNum').text(bossArray.length + ' 人');
    	} else {
    		$('#joinNum').text(personArray.length +' 人');
    	}
    	$('#topContent').html(CONSTS.TYPE[index]).attr('index',index)
    	showType(index)*/
    })
    $("#topRight").click(function() {
    	/*var index = parseInt($('#topContent').attr('index'))
    	if (CONSTS.TYPE.length == index+1) {
    		index = 0
    	} else {
    		index++
    	}
    	if (index == 0) {
    		$('#joinNum').text(bossArray.length + '人');
    	} else {
    		$('#joinNum').text(personArray.length + '人');
    	}
    	$('#topContent').html(CONSTS.TYPE[index]).attr('index',index)
    	showType(index)*/
    })
    function showType(index,content) {
    	if (index == 1) {
    		if(!content) {
    			$("#bottomContent").html(CONSTS.GRADE[0]).attr('index',0)
    			$(".tit_input input").val(1)
    			$("#award").attr('src','img/price0.png')
    			//$(".price_goods").css('display','none')
    		} else {
    			$("#bottomContent").html(CONSTS.GRADE[content]).attr('index',content)
    			if (content == 0) {
    				$(".tit_input input").val(1)
    				$("#award").attr('src','img/price0.png')
    			} else if (content == 1) {
    				$(".tit_input input").val(2)
    				$("#award").attr('src','img/price1.png')
    			} else if (content == 2) {
    				$(".tit_input input").val(5)
    				$("#award").attr('src','img/price2.png')
    			} else if (content == 3) {
    				$(".tit_input input").val(8)
    				$("#award").attr('src','img/price3.png')
    			}
    			//$(".price_goods").css('display','block')
    		}
    	} else {
    		$("#bottomContent").html('').attr('index',-1)
    		$(".tit_input input").val(1)
    		$("#award").attr('src','img/screen.png')
    		//$(".price_goods").css('display','none')
    	}
    }
    $("#bottomRight").click(function() {
    	var index = parseInt($('#bottomContent').attr('index'))
    	if (index >= 0) {
    		if (CONSTS.GRADE.length == index+1) {
    			index = 0
	    	} else {
	    		index++
	    	}
	    	showType(parseInt($('#topContent').attr('index')),index)
    	}
    })
    $("#bottomLeft").click(function() {
    	var index = parseInt($('#bottomContent').attr('index'))
    	if (index >= 0) {
    		if (0 == index) {
    			index = CONSTS.GRADE.length-1
	    	} else {
	    		index--
	    	}
	    	showType(parseInt($('#topContent').attr('index')),index)
    	}
    	console.log(index)
    })
})